<!--尿液分析-->
<template>
  <el-container style="height: 100%; padding: 10px">
    <el-aside width="550px" style="padding: 20px">
      <el-card :body-style="{ overflow: 'auto' }">
        <div style="height: calc(100vh - 120px)">
          <br />
          <user-card v-model:user-data="userInfo"  type="gun"/>
          <br />
          <bluetooth v-model="userInfo" @save="handleRecordSave" />
          <br />
        </div>
      </el-card>
    </el-aside>
    <el-main>
      <el-card :body-style="{ overflow: 'auto' }">
        <div style="height: calc(100vh - 120px)">
          <el-form :model="searchForm" :inline="true">
            <el-form-item label="日期">
              <el-date-picker
                v-model="searchForm.measureTime"
                :clearable="false"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
            <el-form-item label="姓名/身份证">
              <el-input v-model="searchForm.name" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="warning" @click="handleSearch">搜索</el-button>
              <el-button
                type="warning"
                @click="handleSynchronous"
                :loading-icon="Eleme"
                :loading="synchronousStatus"
                >同步</el-button
              >
            </el-form-item>
          </el-form>
          <el-table :data="tableData" :style="{ height: 'calc(100% - 130px)' }">
            <el-table-column prop="userName" label="姓名" />
            <el-table-column prop="cardId" label="项目" />
            <el-table-column prop="sex" label="尿液数据" />
            <el-table-column
              prop="measureTime"
              label="测量时间"
              :formatter="timeFormatter"
            />
          </el-table>
          <el-pagination
            v-model:currentPage="tableProps.pagination.currentPage"
            v-model:page-size="tableProps.pagination.pageSize"
            :page-sizes="[2, 10, 20, 50]"
            layout="sizes, prev, pager, next, jumper"
            :total="tableProps.pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
import {  IHW700TableProps, ISearchParams } from "@/model/BloodType";
import { Eleme } from "@element-plus/icons-vue";
import { computed, reactive, ref, toRaw, watch } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElNotification } from "element-plus";
import { db } from "@/db/db";
// import request from "@/request"
import CardScan from "@/components/CardScan/index.vue";
import UserCard from "@/components/UserCard/index.vue";
import { hwUtils } from "@/utils";
import {Ihw700Cloud} from "@/model/TerminalType";

const timeFormatter = (row, column, cellValue) => {
  if (cellValue) {
    return dayjs(cellValue).format("YYYY-MM-DD HH:mm:ss");
  }
  return "";
};

// 扫码得到的用户信息
const userInfo = ref();
const handleScanSuccess = (data) => {
  userInfo.value = data;
};

/**同步 */
const synchronousStatus = ref(false);
const handleSynchronous = async () => {
  synchronousStatus.value = true;
  try {
    const rows = await db.urinalysis.where("synchronous").equals(0).toArray();
    if (rows.length === 0) {
      ElMessage.closeAll();
      ElMessage.info("暂无可同步的数据！");
      return;
    }
    // const bloodPressureCloudRow = rows.map((item) => {
    //   return {
    //     old_id: item.id,
    //     name: item.userName,
    //     sex: item.sex,
    //     idcard: item.cardId,
    //     bloodleft1: item.diastolic + "",
    //     bloodright1: item.diastolicRight + "",
    //     bloodleft2: item.systolic + "",
    //     bloodright2: item.systolicRight + "",
    //     date: item.measureTime + ""
    //   }
    // })
    // const data = await request({
    //   url: "/xueya",
    //   method: "post",
    //   json: true,
    //   data: bloodPressureCloudRow
    // })
    // if (data && data.data) {
    //   data.data.map(async (item) => {
    //     await getDatabase().hw700.update(item, { synchronous: 1 })
    //   })
    // }
    // ElMessage.closeAll()
    // ElMessage.success("同步成功:" + bloodPressureCloudRow.length + "条数据")
  } catch (e: any) {
    ElMessage.closeAll();
    ElMessage.error("同步失败" + e.msg);
  } finally {
    synchronousStatus.value = false;
  }
};

// const pageService = ()=>{
//   const table =db.bloodPressure;
//   if(searchForm.value.name){
//     table.where("name").
//   }

// }
/**
 * 列表功能，包括搜索
 *
 */

/**------------搜索功能开始----------------- */
const searchForm = ref<ISearchParams>({
  measureTime: [dayjs().startOf("D").valueOf(), dayjs().endOf("d").valueOf()],
  name: "",
});
const tableProps = reactive<IHW700TableProps>({
  pagination: {
    currentPage: 1,
    pageSize: 20,
    total: 0,
  },
});
const searchFormResult = ref({
  name: searchForm.value.name,
  measureTime: searchForm.value.measureTime,
});
const handleSearch = () => {
  searchFormResult.value.name = searchForm.value.name;
  searchFormResult.value.measureTime = searchForm.value.measureTime;
};

const searchData = computed(() => {
  return {
    name: searchFormResult.value.name,
    measureTime: searchFormResult.value.measureTime,
    limit: tableProps.pagination.pageSize,
    offset:
      (tableProps.pagination.currentPage - 1) * tableProps.pagination.pageSize,
  };
});
const tableData = ref<Array<Partial<Ihw700Cloud>>>([]);
watch(
  searchData,
  async (search) => {
    const data = await queryService(toRaw(search));
    tableData.value = data;
  },
  {
    immediate: true,
  }
);
async function queryService(searchItem) {
  const data = await db.hw700
    .where("measureTime")
    .between(
      dayjs(searchItem.measureTime[0]).valueOf(),
      dayjs(searchItem.measureTime[1]).valueOf()
    )
    .filter((item) => {
      if (!searchItem.name) {
        return true;
      }
      if (item.userName && item.userName.indexOf(searchItem.name) !== -1) {
        return true;
      }
      if (item.cardId && item.cardId.indexOf(searchItem.name) !== -1) {
        return true;
      }
      return false;
    })
    .offset(searchItem.offset)
    .limit(searchItem.limit)
    .reverse()
    .toArray();
  return data;
}

const handleRecordSave = async () => {
  try {
    if (!!userInfo.value.cardId === false) {
      ElNotification({
        title: "保存错误",
        message: "无人员信息，不能保存",
        type: "error",
      });
      return;
    }
    if (
      !!userInfo.value.height === false ||
      !!userInfo.value.weight === false
    ) {
      ElNotification({
        title: "错误",
        message: "无身高体重信息，不能保存",
        type: "error",
      });
      return;
    }
    if (userInfo.value.height && userInfo.value.weight) {
      userInfo.value.bim = hwUtils.getBMI(
        userInfo.value.height,
        userInfo.value.weight
      );
      userInfo.value.waistline = hwUtils.getWaistline(
        userInfo.value.height,
        userInfo.value.sex
      );
      userInfo.value.article = "身高体重";
    }
    userInfo.value.synchronous = 0;
    try {
      await db.hw700.put(toRaw(userInfo.value));
    } catch (error) {
      console.error(error);
    }
    // 重置
    userInfo.value = {};
    tableData.value = await queryService(toRaw(searchData.value));
  } catch (error) {
    console.log(error);
  }
};
/**------------搜索功能结束----------------- */

const handleSizeChange = () => {};
const handleCurrentChange = () => {};
</script>
<style scoped lang="scss">
html,
body {
  height: 100%;
}

.el-main {
  padding: 0;
}
</style>
